package sxkyxt.kjyxgs.cn.ishop_gather_uploading_android;

import android.app.Activity;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @version V1.0 <描述当前版本功能>.
 * @filename: sxkyxt.kjyxgs.cn.ishop_gather_uploading_android
 * @Author HY  on {Administrator}.
 * @Org 山西科远信通科技有限公司.
 * @Description: ${TODO} .
 * @Motto 大梦谁先觉, 贫僧我自知..
 * @Date 2018/11/29
 */
public class OkHttpEngine {
    private static OkHttpEngine mInstance;
    private OkHttpClient.Builder mOkHttpClient;

    private String localTempImgDir = "ishop_seller_android";
    public static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");
    public static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    public static OkHttpEngine getInstance() {
        if (mInstance == null) {
            synchronized (OkHttpEngine.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpEngine();
                }
            }
        }
        return mInstance;
    }

    private OkHttpEngine() {
        mOkHttpClient = new OkHttpClient.Builder();

//        File sdcache = getExternalCacheDir();
        //       int cacheSize = 10 * 1024 * 1024;
        mOkHttpClient
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS);
    }

    /**
     * get请求
     */
    public Call getAsynHttp(String url, final Activity activity) {
//        final Dialog dialog = DialogMaker.showCommenWaitDialog(activity, "正在查询 ", null, true, null);
        Request.Builder requestBuilder = new Request.Builder().url(url);
        requestBuilder.method("GET", null); //默认get
        Request request = requestBuilder.build();

        return mOkHttpClient.build().newCall(request);
    }
    /**
     * get请求
     */
    public Response getAsyncHttp(String url) throws IOException {
//        final Dialog dialog = DialogMaker.showCommenWaitDialog(activity, "正在查询 ", null, true, null);
        Request.Builder requestBuilder = new Request.Builder().url(url);
        requestBuilder.method("GET", null); //默认get
        Request request = requestBuilder.build();

        return mOkHttpClient.build().newCall(request).execute();
    }
    /**
     * post 查询请求
     */

    public Call postCallHttp(String url, RequestBody formBody) {
        //        RequestBody formBody = new FormBody.Builder()
//                .add("size", "10")
//                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        return mOkHttpClient.build().newCall(request);
    }

    /**
     * post 查询请求
     */

    public Response postAsyncCallHttp(String url, RequestBody formBody) throws IOException {
        //        RequestBody formBody = new FormBody.Builder()
//                .add("size", "10")
//                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        return mOkHttpClient.build().newCall(request).execute();
    }


    /**
     * 文件下载
     */
    private void downAsynFile(String url) {
//        String url = "http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg";
        Request request = new Request.Builder().url(url).build();
        mOkHttpClient.build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) {
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream = null;
                try {
                    String status = Environment.getExternalStorageState();
                    if (status.equals(Environment.MEDIA_MOUNTED)) {
                        fileOutputStream = new FileOutputStream(new File(Environment
                                .getExternalStorageDirectory() + localTempImgDir + "1.jpg"));
                        byte[] buffer = new byte[2048];
                        int len = 0;
                        while ((len = inputStream.read(buffer)) != -1) {
                            fileOutputStream.write(buffer, 0, len);
                        }
                        fileOutputStream.flush();
                    }
                } catch (IOException e) {
                    Log.i("wangshu", "IOException");
                    e.printStackTrace();
                }

                Log.d("wangshu", "文件下载成功");
            }
        });
    }


    /**
     * 上传 MultipartBody 的文件
     */
    public Call sendMultipartCall(String url , MultipartBody requestBody) {
        // mImgUrls为存放图片的url集合
        // final    File file = new File(Environment.getExternal0StorageDirectory().getPath() + "/Pictures/Screenshots/" + "qwe.png");
//        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
//
//        RequestBody requestBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)
//                .addPart(Headers.of(
//                        "Content-Disposition",
//                        "form-data; name=\"username\""),
//                        RequestBody.create(null, "张鸿洋"))
//                .addPart(Headers.of(
//                        "Content-Disposition",
//                        "form-data; name=\"mFile\"; filename=\"qwe.png\""), fileBody).build();
//
//
//        final Request request = new Request.Builder()
//                .url(url)
//                .post(requestBody)
//                .build();

        //构建请求
        Request request = new Request.Builder()
                .url(url)//地址
                .post(requestBody)//添加请求体
                .build();

        return  mOkHttpClient.build().newCall(request);

    }
    /**
     * <br>对服务器发来的json格式的数据进行格式修正
     * <br>清除掉看不见的隐藏数据
     *
     * @param json
     * @return
     */
    public String cleanErrorCode(String json) {

        if (!json.startsWith("[")) {
            json = json.substring(json.indexOf("["), json.length());
        }
        if (!json.endsWith("]")) {
            json = json.substring(0, json.lastIndexOf("]") + 1);
        }

        return json;
    }
}
